<?php

namespace app\admin\controller;

use app\admin\model\AuthGroup;
use app\api\controller\Client;
use app\common\traits\Page;
use Illuminate\Support\Str;
use nx\Data;
use think\Cache;
use think\Db;
use think\Exception;
use app\admin\model\Users as User_model;
use app\admin\logic\User as User_logic;

/**
 * Class User
 * 通信远程用户中心
 * @package app\admin\controller
 * @author: Huang
 */
class User extends Admin
{
    use Page;

    //远程用户列表
    public static $userClient;

    public function _initialize()
    {
        parent::_initialize();
        self::$userClient = new Client();
    }

    /**
     * 会员显示
     * @return mixed
     */
    public function index()
    {
        $authgroup = new AuthGroup();

        $this->getDepar();
        $where = $this->request->param();
        $wheres = $this->getWhere($where);

        $data = $this->pageshow('users', $wheres, [], $order = 'id desc');

        $data = collect($data);
        foreach ($data as &$vo){
            $re=collect($authgroup->getUserGroup($vo['id']))->pluck('title')->all();
            $vo['auth_text']=join(',',$re);
        }

//        dump($data->all()[0]['auth_text']);
        $this->assign('userdata', $data->all());
        $this->assign('where', $where);
        return $this->fetch();
    }

    /**
     * 条件过滤
     * @param $where
     * @return mixed
     * @author: Huang
     * @internal
     */
    public function getWhere($where)
    {
        // 联系人
        if (!empty($where['username'])) {
            $wheres['username'] = $where['username'];
        }
        // 联系人部门
        if (!empty($where['depar_id'])) {
            $data['depar_id'] = \app\admin\logic\Common::getSondeparId($where['depar_id']);
            if (is_array($data['depar_id'])) {
                $wheres['depar_id'] = ['in', $data['depar_id']];
            } else {
                $wheres['depar_id'] = ['eq', $data['depar_id']];
            }
        }
        // 联系人电话
        if (!empty($where['phone'])) {
            $wheres['phone'] = $where['phone'];
        }
        return $wheres;
    }


    /**
     * 新增会员
     * @return mixed
     */
    public function add()
    {
        if($this->request->isPost()){
            $data=input('post.');
            $arr = session('admin_user');
            logdaily(3,$arr['username'],'新增用户：'.$data['username']);
            $user_logic = new \app\admin\logic\User();
            $result = $user_logic->addUser($data);
            if($result['result'] == 1){
                $this->success($result['msg']);
            }else{
                $this->error($result['msg']);
            }
        }else{
            $depar_logic = new \app\admin\logic\Depar();
            $role_logic = new \app\admin\logic\Role();
            $position = \app\admin\model\Position::all();
            $depars = $depar_logic->getEnabledDeparsToTree();
            $roles = $role_logic->getEnabledRoles();
            $this->assign('depars',$depars);
            $this->assign('roles',$roles);
            $this->assign('position',$position);
            return $this->fetch();
        }
    }

    /**
     * 编辑会员
     * @return mixed
     */
    public function edit()
    {

        if($this->request->isPost()){
            $data=input('post.');
            $arr = session('admin_user');
            logdaily(4,$arr['username'],'修改用户：'.$data['username']);
            $user_logic = new \app\admin\logic\User();
            $result = $user_logic->editUser($data);
            if($result['result'] == 1){
                $this->success($result['msg']);
            }else{
                $this->error($result['msg']);
            }
        }else{
            input('id') ? $id = input('id') : $this->error('缺少参数');
            $userinfo = Db::name('users')->where('id', $id)->find();
            $depar_logic = new \app\admin\logic\Depar();
            $role_logic = new \app\admin\logic\Role();
            $position = \app\admin\model\Position::all();
            $depars = $depar_logic->getEnabledDeparsToTree();
            $roles = $role_logic->getEnabledRoles();
            $userroles = Db::name('AuthGroupAccess')->where('uid',$id)->column('group_id');
            $this->assign('depars',$depars);
            $this->assign('roles',$roles);
            $this->assign('userroles',$userroles);
            $this->assign('userinfo',$userinfo);
            $this->assign('position',$position);
            return $this->fetch();
        }
    }

    /**
     *添加会员
     */
//    public function addrun()
//    {
//        if (!request()->isAjax()) {
//            $this->error('提交方式不正确', url('admin/user/index'));
//        } else {
//            $data = request()->post();
//            $userinfo = collect(self::$userClient->getAllUserInfo())->where('phone', $data['phone'])->first();
//            if (!empty($userinfo)) {
//                $this->error('当前号码已经存在本系统！');
//            }
//            $result = self::$userClient->Client('user', 'adduser', $data);
//            if ($result['result'] == 3) {
//                $this->error($result['msg'], 'otheradduser', $result);
//            } elseif ($result['result'] == 2) {
//                $this->error($result['msg']);
//            } elseif ($result['result'] == 1) {
//                $info['position_id'] =  $data['position'];
//                $info['depar_id'] =  $data['power_deparid'];
//                $info['user_id'] =  $data['id'];
//                try{
//                    Db::name('userdepar')->insert($info);
//                }catch (Exception $exception){
//
//                }
//                $this->setUserAuth($info);
//                Cache::clear('alluser');
//                $this->success('用户添加成功', url('admin/user/index'));
//            }
//        }
//    }

    /**
     * 新增其他系统已经存在的用户
     */
//    public function otheradduser()
//    {
//        if (!request()->isAjax()) {
//            $this->error('提交方式不正确', url('admin/user/index'));
//        } else {
//            $data = request()->post();
//            $result = self::$userClient->Client('user', 'addExistingUser', $data);
//            if ($result['result'] == 2) {
//                $this->error($result['msg']);
//            } elseif ($result['result'] == 1) {
//                $info['position_id'] =  $data['position'];
//                $info['depar_id'] =  $data['power_deparid'];
//                $info['user_id'] =  $data['id'];
//                try{
//                    Db::name('userdepar')->insert($info);
//                }catch (Exception $exception){
//
//                }
//                $this->setUserAuth($info);
//                Cache::clear('alluser');
//                $this->success('用户添加成功', url('admin/user/index'));
//            }
//        }
//    }

    /**
     *编辑会员
     */
//    public function editrun()
//    {
//        if (!request()->isAjax()) {
//            $this->error('提交方式不正确', url('admin/user/index'));
//        } else {
//            $data = request()->post();
//            $result = self::$userClient->Client('user', 'edituser', $data);
//            if ($result['result'] == 2) {
//                $this->error($result['msg']);
//            } elseif ($result['result'] == 1) {
//                $info['position_id'] =  $data['position'];
//                $info['depar_id'] =  $data['power_deparid'];
//                try{
//                    if(Db::name('userdepar')->where('user_id',$data['id'])->find()){
//                        Db::name('userdepar')->where('user_id',$data['id'])->update($info);
//                    }else{
//                        $info['user_id'] =  $data['id'];
//                        Db::name('userdepar')->insert($info);
//                    }
//                }catch (Exception $exception){
//
//                }
//                $info['user_id'] =  $data['id'];
//                $this->setUserAuth($info);
//                Cache::clear('alluser');
//                $this->success('更新添加成功', url('admin/user/index'));
//            } elseif ($result['result'] == 3) {
//                $this->error('电话号码重复,请仔细核对');
//            }
//        }
//    }


    /**
     *禁用会员
     */
//    public function del()
//    {
//        $id = $this->request->param('id', 0);
//        if (empty($id)) {
//            $this->error('请选择要操作的数据!');
//        }
//        $re = self::$userClient->Client('user', 'removeUser', ['id' => $id]);
//        if ($re['result'] == 1) {
//            Cache::clear('allusers');
//            $this->success('删除成功');
//        } else {
//            $this->error('删除失败');
//        }
//    }

    public function del()
    {
        $id = $this->request->param('id', 0);
        $data = Db::name('users')->where('id',$id)->find();
        $arr = session('admin_user');
        logdaily(5,$arr['username'],'删除用户：'.$data['username']);
        $User_logic = new User_logic();
        $result = $User_logic->delUser($id);
        if ($result['result'] === true) {
            $this->success($result['msg']);
        } else {
            $this->error($result['msg']);
        }
    }

    /**
     * 给用户授权角色
     */
//    public function group()
//    {
//        $uid = input('id', 0, 'int');
//        $authgroup = new AuthGroup();
//        $user = self::$userClient->getOneUserById($uid);
//        $auth_groups = $authgroup->getGroups();
//        $user_groups = $authgroup->getUserGroup($uid);
//        $ids = array();
//        foreach ($user_groups as $value) {
//            $ids[] = $value['group_id'];
//        }
//        $this->assign('nickname', $user['username']);
//        $this->assign('auth_groups', $auth_groups);
//        $this->assign('user_groups', implode(',', $ids));
//        return $this->fetch();
//    }


    /**
     * 保存用户的角色列表
     */
//    public function addToGroup()
//    {
//        $uid = $this->request->post('uid');
//        $gid = $this->request->post('group_id/a');
//        if (empty($uid)) {
//            $this->error('参数有误');
//        }
//        $AuthGroup = new AuthGroup();
//        if (is_numeric($uid)) {
//            if (is_administrator($uid)) {
//                $this->error('该用户为超级管理员');
//            }
//            if (empty(self::$userClient->getOneUserById($uid))) {
//                $this->error('用户不存在');
//            }
//        }
//        if ($gid && !$AuthGroup->checkGroupId($gid)) {
//            $this->error($AuthGroup->getError());
//        }
//        if ($AuthGroup->addToGroup($uid, $gid)) {
//            $this->success('操作成功');
//        } else {
//            $this->error($AuthGroup->getError());
//        }
//    }

    public function group()
    {
        $uid = input('id', 0, 'int');
        $authgroup = new AuthGroup();
        $user = Db::name('users')->where('id',$uid)->find();
        $auth_groups = $authgroup->getGroups();
        $user_groups = $authgroup->getUserGroup($uid);
        $ids = array();
        foreach ($user_groups as $value) {
            $ids[] = $value['group_id'];
        }
        $this->assign('nickname', $user['username']);
        $this->assign('auth_groups', $auth_groups);
        $this->assign('user_groups', implode(',', $ids));
        return $this->fetch();
    }

    public function addToGroup()
    {
        $uid = $this->request->post('uid');
        $gid = $this->request->post('group_id/a');
        if (empty($uid)) {
            $this->error('参数有误');
        }
        $AuthGroup = new AuthGroup();
        if (is_numeric($uid)) {
            if (is_administrator($uid)) {
                $this->error('该用户为超级管理员');
            }
//            if (empty(self::$userClient->getOneUserById($uid))) {
            if (empty( Db::name('users')->where('id',$uid)->find() )) {
                $this->error('用户不存在');
            }
        }
        if ($gid && !$AuthGroup->checkGroupId($gid)) {
            $this->error($AuthGroup->getError());
        }
        if ($AuthGroup->addToGroup($uid, $gid)) {
            $this->success('操作成功');
        } else {
            $this->error($AuthGroup->getError());
        }
    }

    /**
     * 获取公共部门方法
     * @internal
     */
    public function getDepar()
    {
        $depar_logic = new \app\admin\logic\Depar();
        $data = $depar_logic->getAllDeparToTree();
        $this->assign('depar', $data);
//        $alldepar = self::$userClient->getAllDepar();
//        $alldepar = Data::tree($alldepar, 'name', 'id', 'pid');
//        $this->assign('alldepar', $alldepar);
        $position = Db::name('position')->where('status', 1)->cache(600)->select();
        $this->assign('position', $position);
    }

    /**
     * 前端客户修改
     * @param $temp
     * @return mixed
     * @author: Huang
     */
    protected function template($temp)
    {
        $auth = $this->hasRole(['superadmin', 'temporaryAdmin', 'commonAdmin']);
        if (is_administrator() || $auth) {
            return $this->fetch($temp);
        } else {
            return $this->fetch('kehu/'.$temp);
        }
    }

    /**
     * 给用户授权角色 根据部门和职位id
     * @param array $info
     */
    protected function setUserAuth(array $info)
    {
        $groupid = Db::name('authgroup_depar_position')
            ->where('depar_id',$info['depar_id'])
            ->where('position_id',$info['position_id'])
            ->value('auth_id');
        if(empty($groupid)){
            return ;
        }
        if(Db::name('auth_group_access')->where('uid',$info['user_id'])->where('group_id',$groupid)->find()){
            return ;
        }
        $_REQUEST['batch'] =true;
        $authgroup = new AuthGroup();
        $authgroup->addToGroup($info['user_id'],$groupid);
    }

    /**
     * 查询部门和职位
     * @param array $userinfo
     * @return array
     * @author: Huang
     */
    public function getDeparandPosition(array $userinfo)
    {
        $authgroup = new AuthGroup();
        foreach ($userinfo as &$vo){
            $info= Db::name('users')->where('id',$vo['id'])->find();
            $vo['position_text'] = getPositionText($info['position_id']);
            $vo['depars_text'] = getDeparText($info['depar_id']);
            $re=collect($authgroup->getUserGroup($vo['id']))->pluck('title')->all();
            $vo['auth_text']=join(',',$re);
            $vo['local_depar_id'] = $info['depar_id'];
        }
        return $userinfo;
    }


    /**
     * 设置部门启用和禁用
     * @return \think\response\Json
     */
    public function setStatus(){
        $id = input('id');
        if(empty($id)){
            $this->error('ID丢失');
        }
        $info = Db::name('users')->where('id',$id)->field('id,status')->find();
        $status = [1,0];
        $data['id'] = $id;
        $data['status'] = $status[$info['status']];
        $res = Db::name('users')->update($data);
        if($res){
            Cache::rm('allUsers');
            $this->success('设置成功');
        }else{
            $this->error('设置失败');
        }
    }

    /**
     * 解绑微信
     */
    public function jiebang(){
        $id = $this->request->param('id',0);
        if ( empty($id) ) {
            $this->error('id参数丢失!');
        }
        if ( is_administrator($id) ) {
            $this->error('不能操作超级管理员!');exit;
        }
        if(User_model::get($id)){
            if(\think\Db::name('users')->where(['id'=>$id])->update(['weixinstatus'=>2,'openid'=>''])){
                $this->success('解绑成功');
            } else {
                $this->error('解绑失败');
            }
        } else {
            $this->error('该用户不存在');
        }
    }

}
